import { I18NType } from '@/app.config'
import { createI18n } from 'vue-i18n'
// import elementZhCn from 'element-plus/dist/locale/zh-cn.mjs'
// import elementEn from 'element-plus/dist/locale/en.mjs'

const langModules = import.meta.glob('./lang/*.ts', { eager: true })
const i18nModules = import.meta.glob('@/**/i18n/*.ts', { eager: true })

const getFileMessage = (list: any, obj: any) => {
    for(let key in list) {
        const messages = list[key].default
        const path = (key.match(/([^/]+)\.ts/) ?? [])[1] ?? ''
        if(messages) {
            obj[path] = {
                ...obj[path],
                ...messages
            }
        }
    }
}

const getAllLanguage = () => {
    const msgObj = {
        [I18NType.EN_US]: {
            // ...elementEn.el
        }, 
        [I18NType.ZH_CN]: {
            // ...elementZhCn.el
        }
    }
    getFileMessage(langModules, msgObj)
    getFileMessage(i18nModules, msgObj)
    return msgObj
}

const getLocalLanguage = () => {
    return sessionStorage.getItem('language') || I18NType.ZH_CN
}

const i18n = createI18n({
    legacy: false, // you must set `false`, to use Composition API
    locale: getLocalLanguage(), // set locale
    messages: getAllLanguage(), // set locale messages
})
document.getElementsByTagName('html')[0].setAttribute('lang', getLocalLanguage() == I18NType.EN_US ? 'en' : 'zh')
export default i18n